//
//  VerifyCarController.swift
//  TrafficViolation
//
//  Created by clover on 2017/5/18.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class VerifyCarController: BaseController {
    
    var flag = 0//标识
    var carPhoto_1:String = ""
    var carPhoto_2:String = ""
    var carPhoto_3:String = ""
    var carPhoto_4:String = ""
    var car:CarModel!
    var cell:CarVerifyViewCell!
    var verifyTableView:UITableView!; //数据表格
    var btn1,btn2,btn3,btn4,submitBtn:UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupNavBar(title: "补充资料", isback: true, appearWay: 3, isright: true)//自定义导航
        verifyTableView=UITableView.init(frame: CGRect(x:0, y:kNavigationBarH + kStatusBarH, width: kScreenW, height: kScreenH-kNavigationBarH - kStatusBarH), style:.plain)
        verifyTableView.delegate=self;//实现代理
        verifyTableView.dataSource=self;//实现数据源
        verifyTableView.rowHeight = commonViewH+7*oTop+2*oLabelH+4*oImgH + cellH + 10
        verifyTableView.register(CarVerifyViewCell.self, forCellReuseIdentifier: "verifycell")
        verifyTableView.layer.accessibilityScroll(.down)
        self.view.addSubview(verifyTableView)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
extension VerifyCarController {
    func choicePicture(sender: UIButton){
        self.flag = sender.tag
        centerY = sender.convert(sender.bounds, to: toast.container).origin.y
        let alert = UIAlertController()
        let cleanAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler:nil)
        let photoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.cameraFunc()
        }
        let choseAction = UIAlertAction(title: "从手机相册选择", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.photoFunc()
        }
        alert.addAction(cleanAction)
        alert.addAction(photoAction)
        alert.addAction(choseAction)
        self.present(alert, animated: true, completion: nil)
    }
    //调用相机
    func cameraFunc(){
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.camera
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: nil)
        }else{
            print("读取相册失败")
        }
    }
    //调用相册
    func photoFunc(){
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: nil)
        }else{
            print("读取相册失败")
        }
    }
    func submitAuth(sender: UIButton){
        if reachability.isReachable {
            let urlString = "\(projectUrl)/car/updateCar/\(car.carid)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            let parameter:[String:Any] = [
                "driveLicense_1":self.carPhoto_1,
                "driveLicense_2":self.carPhoto_2,
                "driveLicense_3":self.carPhoto_3,
                "driveLicense_4":self.carPhoto_4
            ]
            Alamofire.request(urlString, method: .post, parameters: parameter, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    if json["success"] == true {
                        self.dismiss(animated: true, completion: nil)
                    }
                    else{
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                }
                else{
                    print(response.result.error!) //输出错误日志
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
}
extension VerifyCarController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //选择图片成功后代理
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [String : Any]) {
        //显示的图片
        let image:UIImage =  info[UIImagePickerControllerOriginalImage] as! UIImage
        if reachability.isReachable {
            uploadImage(img: image)//上传图片到服务器
            picker.dismiss(animated: true, completion: nil)//图片控制器退出
            toast.showLoadingView(x: oLabelW + oImgW + 10, y: centerY)
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //上传图片
    func uploadImage(img:UIImage){
        let toUrl = "\(projectUrl)/file/upload/carauth/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
        let imageData = UIImageJPEGRepresentation(img, 1.0)!
        //使用Alamofire上传
        Alamofire.upload(multipartFormData: { (mult) in
            mult.append(imageData, withName: "file", fileName: "carauth\(self.flag).png", mimeType: "image/png")
        }, to: toUrl, encodingCompletion: { (result) in
            switch result {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    let jsonString = response.result.value!
                    let jsonDate = JSON(jsonString)
                    if jsonDate["success"] == true {
                        let photoID = jsonDate["rdata"].rawValue as! String
                        let url = "\(projectUrl)/file/download/\(photoID)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
                        if(1 == self.flag){
                            self.carPhoto_1 = photoID
                            self.cell.btn1.sd_setBackgroundImage(with: URL.init(string: url), for: .normal)
                        }
                        if(2 == self.flag){
                            self.carPhoto_2 = photoID
                            self.cell.btn2.sd_setBackgroundImage(with: URL.init(string: url), for: .normal)
                        }
                        if(3 == self.flag){
                            self.carPhoto_3 = photoID
                            self.cell.btn3.sd_setBackgroundImage(with: URL.init(string: url), for: .normal)
                        }
                        if(4 == self.flag){
                            self.carPhoto_4 = photoID
                            self.cell.btn4.sd_setBackgroundImage(with: URL.init(string: url), for: .normal)
                        }
                    }else{
                        self.failOperNoticeFun(code: jsonDate["rcode"].rawString()!, message: jsonDate["rdata"].rawString()!)
                    }
                    toast.closeWin()
                }
            case .failure(let encodingError):
                print("ERROR RESPONSE: \(encodingError)")
            }
        })
    }
}
extension VerifyCarController:UITableViewDataSource, UITableViewDelegate{
    //表头部高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    //底部高度
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        return 0.01
    }
    //行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    //cell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        cell = tableView.dequeueReusableCell(withIdentifier: "verifycell") as? CarVerifyViewCell
        if cell == nil {
            cell = CarVerifyViewCell(style: UITableViewCellStyle.default,reuseIdentifier: "verifycell")
        }
        if !car.drivelicense_1.isEmpty{
            cell.btn1.sd_setBackgroundImage(with: URL.init(string: "\(projectUrl)/file/download/\(car.drivelicense_1)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"), for: .normal)
        }
        if !car.drivelicense_2.isEmpty {
            cell.btn2.sd_setBackgroundImage(with: URL.init(string: "\(projectUrl)/file/download/\(car.drivelicense_2)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"), for: .normal)
        }
        if !car.drivelicense_3.isEmpty {
            cell.btn3.sd_setBackgroundImage(with: URL.init(string: "\(projectUrl)/file/download/\(car.drivelicense_3)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"), for: .normal)
        }
        if !car.drivelicense_4.isEmpty {
            cell.btn4.sd_setBackgroundImage(with: URL.init(string: "\(projectUrl)/file/download/\(car.drivelicense_4)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"), for: .normal)
        }
        return cell!
        
    }
}
